package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.StoreInfoLogic;
import cn.topevery.garden.dal.logic.StoreInoutDetailLogic;
import cn.topevery.garden.entity.impot.StoreInfoImportParam;
import cn.topevery.garden.entity.po.StoreInfo;
import cn.topevery.garden.entity.query.StoreInfoQuery;
import cn.topevery.garden.entity.vo.StoreInfoVO;
import cn.topevery.garden.entity.vo.StoreInoutDetailVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物料库存
 *
 * @author code-generate
 * @date 2021-08-30
 */
@Api(tags = "物料库存接口")
@RestController
@RequestMapping("/storeInfo")
public class StoreInfoController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    StoreInfoLogic storeInfoLogic;

    @Autowired
    StoreInoutDetailLogic storeInoutDetailLogic;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<StoreInfo>> listPage(@RequestBody StoreInfoQuery query) {
        return JsonResult.ok(storeInfoLogic.listPage(query));
    }

    /**
     * 描述 盘点明细列表.
     *
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -09-13 15:56:14 List page by name json result.
     */
    @ApiOperation(value = "盘点明细列表")
    @GetMapping("/listPageByName")
    public JsonResult listPageByName(@RequestParam String name, @RequestParam Integer type) {
        List<StoreInoutDetailVO> list = storeInoutDetailLogic.getListByName(name, type);

        return JsonResult.ok(list);
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(@Valid @RequestBody StoreInfo dto) {
        if(dto.getId() == null){
            boolean isExit = storeInfoLogic.isExit("c_name",dto.getName());
            if(isExit){
                return JsonResult.error(dto.getName() + " 品名规格已存在，请更换名称");
            }
        }
        storeInfoLogic.saveOrUpdate(getUser().id.toString(),dto);
        return JsonResult.ok();
    }

    @ApiOperation("通过Id获取详情")
    @GetMapping("/getInfoById")
    public JsonResult getInfoById(@RequestParam Integer id) {
        StoreInfo storeInfo = storeInfoLogic.getEntity(id);

        return JsonResult.ok(storeInfo);
    }

    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        storeInfoLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(StoreInfoQuery query, HttpServletResponse response) {
        List<StoreInfo> list = storeInfoLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", StoreInfo.class, "", response);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<StoreInfoVO> persons = null;
        try {
            persons = ExcelUtils.importExcel(file, 0, 1, StoreInfoVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<StoreInfoVO> newData = new ArrayList<>();
        for (StoreInfoVO p : persons) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getName() == null) {
                break;
            }
            boolean isExists1 = storeInfoLogic.isExit("c_name", p.getName());
            if (isExists1) {
                anaylsisRes += "品名规格已存在；";
            }

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody StoreInfoImportParam param) {

        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (StoreInfoVO p : param.getTableData()) {
                StoreInfo tmp = new StoreInfo();

                tmp.setName(p.getName());
                tmp.setTypeName(p.getTypeName());
                tmp.setUnit(p.getUnit());
                tmp.setNum(p.getNum());

                storeInfoLogic.saveOrUpdate(user.id.toString(),tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }

}
